# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

# library(MetaboAnalystR)
library(plyr)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(ComplexHeatmap)
library(tidyverse)

options(digits = 3)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

parent <- "z-score"
createWhenNoExist(parent)
scoreFileName <- paste0(parent, "/median_z-score.csv")
scoreData <- read.csv(scoreFileName, header = T, check.names = F, row.names = 1)

sampleInfo <- data.frame(ClassNote = rownames(scoreData))

head(scoreData)

metaColDf <- read_tsv(opt$mc) %>%
select(c("Class", "col"))
metaCols <- metaColDf %>%
deframe()

metaboliteInfo <- read.csv(opt$i, header = T, stringsAsFactors = F, check.names = F) %>%
    select(c("Class", "Metabolite")) %>%
    filter(Name %in% colnames(scoreData))

head(metaboliteInfo)
fileName <- paste0(parent, "/Heatmap_z-score_median.pdf")
pdf(fileName, width = 6, height = 7)
plotData <- scoreData %>%
t()
colors <- colorRampPalette(c("green", "black", "red"), space = "rgb")(256)

sampleColDf <- read.table(opt$sc, header = T, sep = "\t", stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
deframe()

colHa <- HeatmapAnnotation(ClassNote = sampleInfo$ClassNote, col = list(ClassNote = sampleCols),
annotation_legend_param = list(ClassNote = list(nrow = 1, title = "",
labels_gp = gpar(fontsize = 12, fontfamily = "Times"))), show_annotation_name = F
)

rowHa <- rowAnnotation(Class = metaboliteInfo$Class, col = list(Class = metaCols),
annotation_legend_param = list(Class = list(title = "", labels_gp = gpar(fontsize = 12, fontfamily = "Times"))),
annotation_name_gp = gpar(fontsize = 6, fontfamily = "Times"), show_annotation_name = F
)

width = nrow(sampleInfo)
if (width >= 12) {
    width = 12
}

htList <- Heatmap(plotData, col = colors, show_column_names = F, cluster_rows = F, cluster_columns = F,
name = "z-score", top_annotation = colHa, right_annotation = rowHa,
row_names_gp = gpar(fontsize = 6, fontfamily = "Times"),
heatmap_legend_param = list(title_gp = gpar(fontsize = 12, fontfamily = "Times"),
labels_gp = gpar(fontsize = 12, fontfamily = "Times")), show_row_names = F, width = unit(width, "cm")
)
draw(htList, heatmap_legend_side = "right", annotation_legend_side = "top",
padding = unit(c(0.5, 0.5, 0.5, 0.5), "cm")
)
dev.off()


